package fr.didier.template.dnd;

import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.Display;


/**
 * Transfer information in memory (only useable to drag/copy stuff inside the
 * same JVM-Instance)
 */
public class MemoryTransfer extends ByteArrayTransfer {
	private static final String TYPE_NAME = "memory-format"; //$NON-NLS-1$

	private static final int TYPE_ID = registerType(TYPE_NAME);
	
	private long startTime;

	private Object object;


	/**
	 * @return The one and only instance
	 */
	public static MemoryTransfer getInstance() {
		MemoryTransfer instance = (MemoryTransfer) Display.getCurrent().getData( MemoryTransfer.class.getName() + ".MEMORY_TRANSFER"); //$NON-NLS-1$
		if( instance == null ) { 
			instance = new MemoryTransfer();
			Display.getCurrent().setData( MemoryTransfer.class.getName() + ".MEMORY_TRANSFER", instance); //$NON-NLS-1$
		}
		return instance;
	}

	private MemoryTransfer() {
		super();
	}

	@Override
	protected int[] getTypeIds() {
		return new int[] { TYPE_ID };
	}

	@Override
	public String[] getTypeNames() {
		return new String[] { TYPE_NAME };
	}

	@Override
	public void javaToNative(Object object, TransferData transferData) {
		startTime = System.currentTimeMillis();
		this.object = object;
	//	System.out.println("jtn");
		if (transferData != null) {
			super.javaToNative(String.valueOf(startTime).getBytes(),
					transferData);
		}
	}

	@Override
	public Object nativeToJava(TransferData transferData) {
		byte[] bytes = (byte[]) super.nativeToJava(transferData);
	//	System.out.println("ntj");
		if (bytes == null)
			return null;

		try {
			long startTime = Long.parseLong(new String(bytes));
			return this.startTime == startTime ? object : null;
		} catch (NumberFormatException exception) {
			return null;
		}

	}
}
